

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/constant/constant.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/group_details_entity.dart';
import 'package:flutter_ncsjqz_getx/model/login_entity.dart';
import 'package:flutter_ncsjqz_getx/model/user_remark_list_entity.dart';
import 'package:flutter_ncsjqz_getx/page/home/home_logic.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/util/rong_widget.dart';
import 'package:flutter_ncsjqz_getx/util/get_user_util.dart';
import 'package:flutter_ncsjqz_getx/util/time.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/23 10:42
/// filePath： lib/page/rong_im/rong_base_logic.dart
/// desc: 融云基础类控制器，融云所有页面控制器继承此类
/// <summary>
///
class RongBaseLogic extends GetxController {

  ///  会话列表数据
  List<Content> contentList = [];

  /// 融云连接
  void rongConnect() async {
    if (await RongIMClient.getConnectionStatus() == 0) {
      print('融云已经连接中${RongIMClient.getConnectionStatus()}');
    }else{
      LoginData? loginData = getUserUtil();
      //连接融云
      RongIMClient.connect(loginData.ryToken ?? '', (int? code, String? userId) async{
        print('融云连接 token ${loginData.ryToken}');
        print('融云连接 result ' + code.toString());
        if (code == 0) {
          print("融云连接成功 userId：" + userId!);
          // 获取融云会话列表
          getConversationList();
          // 订阅会话通知 别人发消息来 进行接收
          getConversationUpdateListEvent();
          // 连接成功后打开数据库
          // _initUserInfoCache();
        } else if (code == 31004) {
          // token 非法
          toast("Token非法，请检查融云Token");
        }
      });
    }
  }

  /// 获取所有未读数
  void getTotalUnreadCount(Function(int? count)? finished) {
    RongIMClient.getTotalUnreadCount((int? count, int? code) {
      if (0 == code) {
        print("融云消息未读数为" + count.toString());
        finished!(count);
      }
    });
  }

  /// 订阅私聊会话列表监听 - 发消息来才触发 更新会话列表
  void getConversationUpdateListEvent() async{
    // 订阅 eventbus , 对融云消息进行监听
    Constant.eventBus.on<EventFn>().listen((event) async {
      if(event.name=="rong"){
        getConversationList(event: event);
      }
    });
  }

  /// 获取会话列表
  /// event 只有来消息才有值，为空则为下拉刷新或启动app时渲染
  void getConversationList({event}) async{
    if(event == null){ /// 不是来消息通知，清空  防消息通知重复
      contentList = [];
    }

    // 更新消息数量
    getTotalUnreadCount((count) {
      Constant.msgCount = count;
      var holog = Get.put(HomeLogic());
      holog.update();
    });

    // 会话id
    List targetIds = [];
    // 是否存在某个会话
    int indexWhere = -1;
    // 获取会话列表
    List? conversation = await onGetConversationList();
    Message? message;

    if (conversation != null ) {
      // 拿到每个会话id
      for (Conversation con in conversation)  targetIds.add(con.targetId);

      // event不为空 = 来消息了
      if(event!=null && event.value['left'] == 0){
        message = event.value["message"];
        indexWhere = contentList.indexWhere((element) => element.targetId == message!.targetId);
      }

      // 查询是否免打扰 只加载通讯录好友的消息
      UserRemarkListEntity chatImageRemarkEntity = await DioService<UserRemarkListEntity>().queryUserRemarkList ({
        'userIds': event == null ? targetIds : [message!.targetId],
      });
      if (chatImageRemarkEntity.code == 0) {
        for (int i = 0; i < chatImageRemarkEntity.data!.length; i++) {
          // 新消息提示框，检验是否免打扰  免打扰不弹窗
          if(chatImageRemarkEntity.data![i].isDisturb!=null && !chatImageRemarkEntity.data![i].isDisturb! && message!=null){
            BotToast.showCustomNotification(
              duration: Duration(seconds: 3),
              toastBuilder: (void Function() cancelFunc) {
                Conversation? messageContent = getMessageContentById(message!.targetId, conversation);
                return Material(
                  child: InkWell(
                    child: Container(
                      width: Get.width  - 30,
                      height: 50,
                      padding: EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10),
                        boxShadow: [
                          BoxShadow(color: Colors.grey.shade400,spreadRadius: 2,blurRadius: 3),
                        ],
                      ),
                      alignment: Alignment.center,
                      child: Row(
                        children: [
                          RongWidget.imgNet("${chatImageRemarkEntity.data![i].picUrl}",width: 30,height: 30,borderRadius: BorderRadius.circular(5)),
                          Expanded(
                            child: RongWidget.title(
                              "  ${chatImageRemarkEntity.data![i].menuMessageType == 1 ?
                              chatImageRemarkEntity.data![i].remarkName :
                              chatImageRemarkEntity.data![i].groupName}: ${messageContent.originContentMap==null ?
                              messageContent.latestMessageContent!.conversationDigest():
                              messageContent.originContentMap!['message']}",
                            ),
                          ),
                        ],
                      ),
                    ),
                    onTap: (){
                      print("点击了通知");
                    },
                  ),
                  color: Colors.transparent,
                );
              },
            );
          }

          // 在列表里面查找当前id 如果没有则是新增
          if(event == null) indexWhere = contentList.indexWhere((element){
            if(chatImageRemarkEntity.data![i].menuMessageType == 1 ){
              // 单聊
              return element.targetId == chatImageRemarkEntity.data![i].ryUserId;
            }else{
              // 群聊
              return element.targetId == chatImageRemarkEntity.data![i].groupId;
            }
          });

          // 目标id
          // menuMessageType = 1单聊 or 2群聊
          String targetId = chatImageRemarkEntity.data![i].menuMessageType == 1 ? chatImageRemarkEntity.data![i].ryUserId : chatImageRemarkEntity.data![i].groupId;

          // 解析每个会话
          Conversation? messageContent = getMessageContentById(targetId, conversation);

          // 组装解析出来的会话内容
          Content content = Content(
            cover: chatImageRemarkEntity.data![i].picUrl,
            // digest: digest,
            isTop: messageContent.isTop!?0:1,
            intimer: messageContent.sentTime,
            digestCount: messageContent.mentionedCount,
            nickName: chatImageRemarkEntity.data![i].menuMessageType == 1 ? chatImageRemarkEntity.data![i].remarkName : chatImageRemarkEntity.data![i].groupName,
            noDisturb: messageContent.blockStatus == 0,
            timer: TimeUtil.convertTime(messageContent.sentTime!),
            message: messageContent.originContentMap==null?messageContent.latestMessageContent?.conversationDigest()??"":messageContent.originContentMap!['message'],
            targetId: chatImageRemarkEntity.data![i].menuMessageType == 1 ? chatImageRemarkEntity.data![i].ryUserId : chatImageRemarkEntity.data![i].groupId,
            messageId: messageContent.latestMessageId.toString(),
            myUserId: messageContent.senderUserId,
            userId: chatImageRemarkEntity.data![i].userId,
            count: messageContent.unreadMessageCount,
            draft: messageContent.draft,
            menuMessageType: chatImageRemarkEntity.data![i].menuMessageType,
            urls: chatImageRemarkEntity.data![i].urls ?? [],
          );

          //集合里面没有当前目标人的id 需要添加
          if (indexWhere == -1) {
            contentList.insert(0, content);
          }else{
            contentList.removeAt(indexWhere);
            contentList.insert(0, content);
          }
        }
      }
    }
    update();
  }

  /// 获取对话列表
  Future onGetConversationList() async {
    return await RongIMClient.getConversationList([RCConversationType.Private,RCConversationType.Group,RCConversationType.System,]);
  }

  /// 解析单条会话
  Conversation getMessageContentById(id,List list){
    dynamic messageContent;
    for(int i=0;i<list.length;i++){
      if(id==list[i].targetId){
        messageContent=list[i];
        break;
      }
    }
    return messageContent;
  }

  /// 获取本地历史消息
  Future getHistoryMessage(int conversationType,String privateUserId,int messageId,int pageSize) async {
    return await RongIMClient.getHistoryMessage(conversationType, privateUserId, messageId, pageSize);
  }

  /// 获取远端历史消息
  void getRemoteHistoryMessages(privateUserId) {
    RongIMClient.getRemoteHistoryMessages(1, privateUserId, 0, 20, (List? msgList, int? code){
      if (code == 0) {
        for (Message msg in msgList!) {
          print("获取融云远端消息  success " + msg.messageId.toString());
        }
      } else {
        print("获取融云远端消息 error " + code.toString());
      }
    });
  }

  /// 设置系统Notification免打扰 需配合Notification使用
  /// conversationType == 1 (单聊), conversationType == 3（群聊）
  setConversationNotificationStatus(conversationType, targetId, isBlocked,) async{
    //消息免打扰
    RongIMClient.setConversationNotificationStatus(conversationType, targetId, isBlocked, (int? status, int? code) {
      print("setConversationNotificationStatus1 status " + status.toString());
      // String toast = code == 0 ? "${isBlocked?'设置':'取消'}免打扰成功" : "${isBlocked?'设置':'取消'}免打扰失败，错误码: $code";
      // BotToast.showText(text: toast);
    });
  }

  /// 清空聊天记录
  void deleteMessages(targetId,Function onCall,{int? rcConversationType})async{
    RongIMClient.clearMessages(rcConversationType ?? RCConversationType.Private, targetId.toString(),(int? code) {
      if(code==0){
        BotToast.showSimpleNotification(title: "清空聊天记录成功");
        onCall(0);
      }else{
        BotToast.showSimpleNotification(title: "清空聊天记录失败",);
        onCall(0);
      }
    });
  }

  /// 发送消息
  void sendTextMsg(int conversationType,String msg,String targetId) async{
    int? status= await RongIMClient.getConnectionStatus();
    if(status == 0  && msg.length>0){
      TextMessage txtMessage = new TextMessage();
      //消息内容
      txtMessage.content = msg;
      MentionedInfo mentionedInfo = new MentionedInfo();
      mentionedInfo.type = RCMentionedType.Users;
      List<String> list=[];
      //查看当前userIdList里面 从消息内容字符串获取所有字符串 里面是否有这些人
      // userIdList.forEach((element) {
      //   int index =msg.indexOf(element.userName);
      //   if(index!=-1){
      //     list.add(element.userId);
      //     print(element.userName);
      //   }
      // });
      mentionedInfo.userIdList = list;
      mentionedInfo.mentionedContent = "";
      // @通知好友
      txtMessage.mentionedInfo = mentionedInfo;
      Message? message  =await RongIMClient.sendMessage(conversationType, targetId, txtMessage,disableNotification: true);
      setMessageSentStatus(message!.messageId!, conversationType);
    }
  }

  /// 发送文件消息
  void onSendFileMessage({String? localPaht,int? conversationType,String? targetId,String? fileType}) async {
    // localPath 为文件本地路径,注意 Android 必须以 file:// 开头
    FileMessage fileMessage = FileMessage.obtain(localPaht!);
    // 文件后缀如 "png" "txt"
    fileMessage.mType = fileType!;
    Message? message = await RongIMClient.sendMessage( conversationType!, targetId!, fileMessage);
    RongIMClient.setMessageSentStatus(message!.messageId!, conversationType, (code) async{
      print("发送状态 result:$code");
    });
  }

  /// 发送语音
  void sendVoiceMessage(path,duration,{conversationType,privateUserId,Function? sendCall})async{
    VoiceMessage msg = VoiceMessage.obtain(path, duration);
    Message? message = await RongIMClient.sendMessage(conversationType, privateUserId, msg);
    RongIMClient.onMessageSend=(int? messageId, int? status, int? code)async{
      sendCall!(status,messageId);
    };
  }

  /// 消息状态
  void setMessageSentStatus(messageId,conversationType){
    RongIMClient.setMessageSentStatus(messageId, conversationType, (code) async{
      print("消息发送状态 result:$code");
      getConversationList();
    });
  }

  /// 消息已读
  void sendReadReceiptMessage(conversationType, privateUserId)async{
    //清除未读消息
    bool success = await RongIMClient.clearMessagesUnreadStatus(conversationType, privateUserId) ?? false;
    if(success){
      print('已读');
    }else{
      print(success);
    }
    //设置草稿信息
    // textEditingController.value.text = await RongIMClient.getTextMessageDraft(conversationType, privateUserId);
  }

  /// 删除会话
  void deleteContent(targetId){
    RongIMClient.removeConversation(RCConversationType.Private, targetId, (success) {
      if(success!) {
        print("删除会话成功");
        update();
      }
    });
  }

  void getConnectionStatus()  async{
    RongIMClient.onConnectionStatusChange = (int? connectionStatus) {
      if (RCConnectionStatus.KickedByOtherClient == connectionStatus ||
          RCConnectionStatus.TokenIncorrect == connectionStatus ||
          RCConnectionStatus.UserBlocked == connectionStatus) {
        // SpUtil.remove(Constants.loginData);
        toast('登陆失效,请重新登陆');
        // Get.to(Login());
      } else if (RCConnectionStatus.Connected == connectionStatus) {
        update();
      }else{
      }
    };
  }

  /// 消息监听器
  static void listenerMessage(){
    //消息接收回调
    print('listenerMessage:init');
    RongIMClient.onMessageReceivedWrapper =  (Message? msg, int? left, bool? hasPackage, bool? offline) async {
      print("receive message messsageId:" + msg!.messageId.toString() + " left:" + left.toString());
      print('收到消息');
      //发送到消息列表
      if(msg.conversationType != RCConversationType.ChatRoom){
        print("5555");
        //聊天室消息不需要计算
        // updateNumber(false);
        // bus.send(Constants.updateNumber,[]);
      }
      // 发送eventBus事件信息
      Constant.eventBus.fire(EventFn("rong",{'message': msg, 'left': left,}));
    };
  }

  /// 断开 IM 连接
  static void disconnect(bool needPush){
    //needPush 断开连接之后是否需要远程推送
    RongIMClient.disconnect(needPush);
  }

  /// 获取群信息
  Future<GroupDetailsData> getGroup(groupId) async{
    GroupDetailsEntity groupDetailsEntity =await DioService<GroupDetailsEntity>().getGroup({'groupId':groupId});
    if(groupDetailsEntity.code == 0){
      return groupDetailsEntity.data!;
    }
    return GroupDetailsData();
  }
}


//列表内容
class Content{
  String? cover;//头像
  String? nickName;//昵称
  String? message;//最新消息内容
  String? timer;//发送时间
  bool? noDisturb;//是否免打扰
  String? targetId;//目标人的id
  String? messageId;//消息id
  String? myUserId;//我的id
  int? userId;//我的id
  int? count;//未读消息
  String? draft;//草稿箱
  List<dynamic>? urls;//头像集合
  int? menuMessageType;//类型判断
  String? digest;//艾特我字符串
  int? digestCount;//艾特我的数量
  int? isTop;//是否置顶  0置顶 1不是置顶
  int? intimer;//时间戳

  Content({this.message,this.timer,this.intimer,this.isTop:1,this.nickName,this.cover,this.noDisturb,this.targetId,this.messageId,this.myUserId,this.userId,this.count,this.draft,this.urls,this.digestCount,this.menuMessageType,this.digest});
}